//
//  OrderDetailsViewModel.swift
//  Pods
//
//  Created by eme on 2017/3/31.
//
//
/** 
 订单详情ViewModel
 */
import RxSwift
import NetWorkCore
import SwiftyJSON
import ModelProtocol

class OrderDetailsViewModel{
    
    let getOrderDetails = PublishSubject<String>()
    
    let getOrderKD = PublishSubject<String>()
    
    let kdbackDate = PublishSubject<KuaidiModel>()
    
    let backDate = PublishSubject<OrderDetailsModel>()
    
    let disposeBag = DisposeBag()
    
    let error = PublishSubject<MikerError>()
    
    let refreshing = Variable(false)
    
    var iscanevaluate = ""
    
    let loading : Observable<Bool>
    
    init (){
        
        let requestIndicator = ActivityIndicator()
        self.loading = requestIndicator.asObservable()
        
        let request = getOrderDetails.map{ orderid in
            
            return MineApi.getOrderDetails(orderID: orderid,iscanevaluate: self.iscanevaluate)
            
            }.shareReplay(1)
        
        let response = request.emeRequestApiForObj(OrderDetailsModel.self, activityIndicator: requestIndicator).shareReplay(1)
        
        response.subscribe(onNext:{[unowned self] result in
            
            switch result{
                
            case .success(let data):
                
                self.backDate.onNext(data)
                
            case.failure(let error):
                
                self.error.onNext(error)
                
            }
            
        }).addDisposableTo(disposeBag)
        
        let getkdrequest = getOrderKD.map{orderid in
            
            return MineApi.getOrderKD(id: orderid)
            
            }.shareReplay(1)
        
        let kdresponse = getkdrequest.emeRequestApiForObj(KuaidiModel.self).shareReplay(1)
        
        kdresponse.subscribe(onNext:{[unowned self] result in
            switch result{
            case .success(let data):
                self.kdbackDate.onNext(data)
            case .failure(let error):
                self.error.onNext(error)
            }
        }).addDisposableTo(disposeBag)
        
        
        
        Observable
            .of(
                request.map { _ in true },
                response.map { _ in false },
                error.map { _ in false }
            )
            .merge()
            .bindTo(refreshing)
            .addDisposableTo(disposeBag)
    }
    
    
}
